package com.derekandbritt.booST;

import java.util.Date;

import com.derekandbritt.booST.data.Challenge;
import com.derekandbritt.booST.exceptions.ConnectionException;
import com.derekandbritt.booST.exceptions.DataFormatException;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class SendChallenge extends booSTActivity {

	public final static String RECIPIENT_KEY = "com.derekandbritt.booST.recipient";
	
	private String recipientId;
	
	@SuppressWarnings("unchecked")
	public void displayContent() throws ConnectionException, DataFormatException {
		
		this.setContentView(R.layout.send);
    	
		recipientId = this.getIntent().getExtras().getString(RECIPIENT_KEY);
		
		configurePersonalStatus();
		configureFriendsStatus(recipientId);
		
    	Spinner type = (Spinner)this.findViewById(R.id.ChallengeTypeSpinner);
    	ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, Challenge.Type.values());
    	type.setAdapter(spinnerArrayAdapter);
    	type.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
				TableRow row = (TableRow)findViewById(R.id.TimeLimitRow);
				if(position == 0) {
					row.setVisibility(View.INVISIBLE);
				} else {
					row.setVisibility(View.VISIBLE);
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) { }
		});
    	
    	final TextView expirationText = (TextView) this.findViewById(R.id.Expiration);
    	SeekBar expirationBar = (SeekBar)this.findViewById(R.id.ExpirationSlider);
    	expirationBar.setMax(10);
    	expirationBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onProgressChanged(SeekBar seekbar, int progress, boolean fromTouch) {
				int days = progress / 2;
				int halves = progress % 2;
				
				StringBuffer buffer = new StringBuffer();
				buffer.append(days + "." + (halves * 5) + " day");
				if(days != 1 || halves != 0) { buffer.append("s"); }
				
				expirationText.setText(buffer.toString());
			}

			public void onStartTrackingTouch(SeekBar seekbar) { }
			public void onStopTrackingTouch(SeekBar seekbar) { }
    	});
    	
    	final TextView distanceText = (TextView) this.findViewById(R.id.Distance);
    	SeekBar distanceBar = (SeekBar)this.findViewById(R.id.DistanceSlider);
    	distanceBar.setMax(50);
    	distanceBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onProgressChanged(SeekBar seekbar, int progress, boolean fromTouch) {
				int miles = progress / 10;
				int tenths = progress % 10;
				
				StringBuffer buffer = new StringBuffer();
				buffer.append(miles + "." + tenths + " mile");
				if(miles != 1 || tenths != 0) { buffer.append("s"); }

				distanceText.setText(buffer.toString());
			}

			public void onStartTrackingTouch(SeekBar seekbar) { }
			public void onStopTrackingTouch(SeekBar seekbar) { }
    	});
    	
    	final TextView timeLimitText = (TextView) this.findViewById(R.id.TimeLimit);
    	SeekBar timeLimitBar = (SeekBar)this.findViewById(R.id.TimeLimitSlider);
    	timeLimitBar.setMax(120);
    	timeLimitBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onProgressChanged(SeekBar seekbar, int progress, boolean fromTouch) {
				int hrs = progress / 60;
				int min = progress % 60;
				
				StringBuffer buffer = new StringBuffer();
				buffer.append(hrs + " hr");
				if(hrs != 1) { buffer.append("s"); }
				buffer.append(" " + min + " min");
				
				timeLimitText.setText(buffer.toString());
			}

			public void onStartTrackingTouch(SeekBar seekbar) { }
			public void onStopTrackingTouch(SeekBar seekbar) { }
    	});
    	
    	Button cancel = (Button)this.findViewById(R.id.CancelChallengeButton);
    	cancel.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				finish();
			}
		});
    	
    	Button send = (Button)this.findViewById(R.id.SendChallengeButton);
    	send.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				
				try {
					issueChallenge();
					Toast.makeText(view.getContext(), "Challenge Sent!", Toast.LENGTH_SHORT).show();
				} catch (DataFormatException e) {
					handleError(e);
				} catch (ConnectionException e) {
					handleError(e);
				}
			}
		});
    	
	}
	
	private void issueChallenge() throws DataFormatException, ConnectionException {
		
		Spinner typeList = (Spinner)this.findViewById(R.id.ChallengeTypeSpinner);
		SeekBar expirationBar = (SeekBar)this.findViewById(R.id.ExpirationSlider);
		SeekBar distanceBar = (SeekBar)this.findViewById(R.id.DistanceSlider);
		SeekBar timeLimitBar = (SeekBar)this.findViewById(R.id.TimeLimitSlider);
		
		// TODO fix the time limit to not error check when it is hidden
		Challenge.Type type = Challenge.Type.COMPETITIVE;
		if(Challenge.Type.COOPERATIVE.getName().equals(typeList.getSelectedItem().toString()))
			type = Challenge.Type.COOPERATIVE;
		
		
		if(expirationBar.getProgress() == 0)
			throw new DataFormatException("Expiration must be greater than 0.5 days.");
		else if(distanceBar.getProgress() == 0)
			throw new DataFormatException("Distance must be greater than 0.1 miles.");
		else if(timeLimitBar.getProgress() == 0  && type == Challenge.Type.COOPERATIVE)
			throw new DataFormatException("Duration must be greater than 1 minute.");
		
		int expirationHours = expirationBar.getProgress() * 12;
		double distance = ((double)distanceBar.getProgress()) / 10.0;
		Date currentDate = new Date(System.currentTimeMillis());
		Date expirationDate = new Date(System.currentTimeMillis() + (expirationHours * 3600000));
		
		Challenge challenge = new Challenge();
		challenge.setSender(osEndpoint.getPersonId());
		challenge.setReceiver(recipientId);
		challenge.setTimeIssued(currentDate);
		challenge.setLastUpdated(currentDate);
		challenge.setStatus(Challenge.Status.PENDING);
		challenge.setType(type);
		challenge.setExpiration(expirationDate);
		challenge.setDistance(distance);
		
		if(type == Challenge.Type.COOPERATIVE)
			challenge.setTimeLimit(timeLimitBar.getProgress());
		
		setChallenge(challenge, true);
	}
	
}
